package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dao.SetmealDao;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.Setmeal;
import com.itheima.domain.SetmealDish;
import com.itheima.dto.SetmealDishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealControlller {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealService setmealService;         // 套餐


    @Autowired
    private SetmealDishService setmealDishService;//  套餐菜品

    @Autowired
    private SetmealDao setmealDao;  //dao层

    @Autowired
    private DishService dishService;


    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("新增套餐信息：{}",setmealDto);

        //
        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }


    /**
     * 分页查询套餐
     * @param page      //当前页码
     * @param pageSize  //每页展示条数
     * @param name      //模糊条件
     * @return
     */
    @GetMapping("/page")
    public Page page(int page, int pageSize, String name){

        //构造分页构造器
        Page<Setmeal> pageInfo = new Page<Setmeal>(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<Setmeal>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //更新时间降序排
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //调用方法查询数据
        setmealService.page(pageInfo,queryWrapper);

        //创建Page<SetmealDto>对象
        Page<SetmealDto> dtoPage = new Page<SetmealDto>();
        // 对象拷贝   排除 records补不拷贝
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        //获取records集合
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId(); //分类id
            Category category = categoryService.getById(categoryId); //套餐对象
            //健壮性判断
            if(category !=null ){
                //分类套餐名称 设置到 套餐属于的套餐名
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }

            return setmealDto;
        }).collect(Collectors.toList());

        //设置records值
        dtoPage.setRecords(list);

        return  dtoPage;
    }


    /**
     * 根据id删除 （单个或批量）
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){

        log.info("ids数据为：{}",ids);

        setmealService.deleteWithSetmealDish(ids);

        return R.success("套餐删除成功");
    }

    /**
     *
     * 批量 启用 或 停售
     * @param status
     * @param ids
     * @return
     */

    @PostMapping("/status/{status}")
    public R<String> updateSta(@PathVariable int status, Long[] ids){
        //
        //log.info("type:{}+ids:{}",status,ids.length);

        //自定义方法
        setmealService.updateStatus(status,ids);

        return  R.success("修改成功");
    }

    /**
     * 根据id回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getWithSetDish(@PathVariable Long id){

        SetmealDto setmealDto = setmealService.getWithSetmealDish(id);

        return R.success(setmealDto);
    }


    /**
     * 根据id修改数据
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody SetmealDto setmealDto){
        log.info("setmealDto修改数据:{}",setmealDto.toString());
        //
        setmealService.updateWithSetmealDish(setmealDto);
        return R.success("修改成功");

    }

    /**
     * 根据Setmeal表中 category_id 查询具体套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){

        //构造条件构造器
        /*List<Setmeal> list = new LambdaQueryChainWrapper<>(setmealDao).eq(setmeal.getCategoryId() != null,
                Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(Setmeal::getStatus, 1)
                .orderByAsc(Setmeal::getUpdateTime)
                .list();
        return  R.success(list);*/

        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() !=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        queryWrapper.orderByAsc(Setmeal::getUpdateTime);

        // SQL： select * from setmeal where category_id = ? and stasus = 1
        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }


    /**
     * 根据套餐id 查询 菜品套餐关联表数据setmeal_id 字段
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<SetmealDishDto>> list(@PathVariable Long id) {   //套餐菜品关联表setmeal_dish表  setmeal_id字段
        //
        log.info("当前套餐id:{}", id);

        //构建条件构造器
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id !=null,SetmealDish::getSetmealId,id);
        // SQL: Select * from setmeal_dish where setmeal_id = ?
        List<SetmealDish> list = setmealDishService.list();

        List<SetmealDishDto> setmealDishDtoList = list.stream().map(item -> {
            SetmealDishDto setmealDishDto = new SetmealDishDto();  //创建空对象
            BeanUtils.copyProperties(item, setmealDishDto);         //数据拷贝

            Long dishId = item.getDishId();           //菜品id
            Dish dish = dishService.getById(dishId);

            if (dish != null) {
                String image = dish.getImage();             //获取 菜品图片
                String description = dish.getDescription(); //获取  菜品描述

                setmealDishDto.setImage(image);
                setmealDishDto.setDescription(description);
            }

            return setmealDishDto;

        }).collect(Collectors.toList());

        return  R.success(setmealDishDtoList);

    }

}
